package com.kiln.juxingqs.ui.vm

import android.app.Application
import android.net.Uri
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import client.global.commlib.comm_ui.bean.CommImg
import client.global.commlib.network.data.JsonResult
import client.global.commlib.network.data.Ret
import client.global.commlib.out_time
import client.global.commlib.toast.toast
import client.global.commlib.utils.StoreUtil
import client.global.commlib.utils.Util
import com.kiln.juxingqs.api.bean.*
import com.kiln.juxingqs.ui.viewmodel.MiddleVm

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import retrofit2.Response

class MainViewModel(app: Application) : MiddleVm(app) {

    val isShowing = MutableLiveData<Boolean>(false)
    val isShowNotiDialog = MutableLiveData<Boolean>(true)
    val cutTab = MutableLiveData<String>("0")
    val userAvatar = MutableLiveData<Uri>()
    val cateId = MutableLiveData<String>("")

    val callUser = MutableLiveData<JsonResult<UserInfo>>()

    val isCheckAll = MutableLiveData<Boolean>(false)
    val isEditMode = MutableLiveData<String>("编辑")
    val isEditModeVal = MutableLiveData<Boolean>(true)

    val callBuyCart = MutableLiveData<JsonResult<BuyCartRet>>()
    val homeCall = MutableLiveData<JsonResult<GoodsIndex>>()
    val tradeCall = MutableLiveData<JsonResult<GoodsIndex>>()

    val adCall = MutableLiveData<JsonResult<CommImg>>()
    val NotiCall = MutableLiveData<JsonResult<Norification>>()
    val zxCall = MutableLiveData<JsonResult<ArticleInfo>>()
    val delRet = MutableLiveData<JsonResult<Ret>>()
    val isCateLoading = MutableLiveData<Boolean>(false)
    val callCate = MutableLiveData<JsonResult<CateGoods>>()
    val rechargeOrder = MutableLiveData<JsonResult<CurrentRechargeOrder>>()
    val rechargeOrderList = MutableLiveData<JsonResult<CurrentRechargeOrder>>()

    val switchValue = MutableLiveData<Int>(-1)


    /**
     */
    fun homeOnNoti() {
        viewModelScope.launch {
            flow {
                var emm: Response<JsonResult<Norification>>? = null
                out_time {
                    val ret = server.get_notification()
                    emm = ret
                }

                emit(emm)
            }.map {
                var emm: Response<JsonResult<GoodsIndex>>? = null
                it?.body()?.let {
                    if (it.isSuccess) {

                        NotiCall.postValue(it)
                        out_time {
                            val ret = server.goods_index()
                            emm = ret
                        }
                    }
                }
                emm
            }.flowOn(Dispatchers.IO)
                .catch { cause ->
                    if (cause != null) {
                        toast(cause.message)
                    }
                }.collectLatest {
                    homeCall.value = it?.body()

                }
        }
    }

    fun storeList() {
        hold({
            server.trade_index(deal_status = "1")
        }, success = {
            tradeCall.value = it
        })
    }

    fun tradeList() {
        hold({
            server.trade_index()
        }, success = {
            tradeCall.value = it
        })
    }

    fun getCommImg() {
        hold({
            server.common_img()
        }, {
        }, {
            adCall.value = it
        })
    }

    fun zxInfo() {
        hold({
            server.article_info()
        }, {
        }, {
            zxCall.value = it
        })
    }

    fun holdCateChild(
        cate: String,
        page: Int,
        callCate: MutableLiveData<JsonResult<CateGoods>>,
        isLoading: MutableLiveData<Boolean>
    ) {
        hold({
            server.goods_type_detail(page, cate)
        }, {
            isLoading.value = true
        }, {
            callCate.value = it
        }, complete = {
            isLoading.value = false
        })
    }

    fun holdCate() {
        if (isCateLoading.value!!)
            return
        hold({
            server.goods_type_detail(1, "0")
        }, {
            isCateLoading.value = true
        }, {
            callCate.value = it
        }, complete = {
            isCateLoading.value = false
        })
    }

    fun callBuyCart() {
        hold({
            server.shopping_cart()
        }, {
        }, {
            callBuyCart.value = it
        })
    }

    fun delCart(list: ArrayList<BuyCartRet.Shopping>) {
        hold({
            var goods_sku_idS = ""
            for (i in list) {
                goods_sku_idS += "${i.shopping_id},"
            }
            server.del_shopping_cart(goods_sku_idS)
        }, {
            isShowing.value = true
        }, {
            delRet.value = it
        }, complete = {
            isShowing.value = false
        })
    }


    fun setAvatar(lo: LifecycleOwner) {
        if (userAvatar.value == null) {
            toast("请选择图片")
            return
        }
        isShowing.value = true
        viewModelScope.launch {
            flow {
                var emm: Response<JsonResult<UploadRet>>? = null
                val file = Util.getLuBan(
                    lo,
                    userAvatar.value!!
                )
                val requestFile: RequestBody = RequestBody.create(
                    "multipart/form-data".toMediaTypeOrNull(),
                    file
                )
                val body = MultipartBody.Part.createFormData(
                    "file",
                    file.name,
                    requestFile
                )
                val descriptionString = "file"
                val description = RequestBody.create(
                    "multipart/form-data".toMediaTypeOrNull(),
                    descriptionString
                )
                out_time {
                    val ret = server.upload(description, body)
                    emm = ret
                }
                emit(emm)
            }.map {
                var emm: JsonResult<Ret>? = null
                it?.body()?.let {
                    if (it.isSuccess) {
                        out_time {
                            val ret = server.user_avatar(it.data!!.url)
                            emm = ret?.body()
                        }
                    } else {
                        emm = JsonResult<Ret>().apply {
                            message = it.message
                        }
                    }
                }
                emm
            }.flowOn(Dispatchers.IO).onCompletion { cause ->
                isShowing.value = false
            }.catch { cause ->
                if (cause != null) {
                    toast(cause.message)
                }
            }.collectLatest {
                it?.let {
                    if (it.isSuccess) {
                        toast("设置成功")
                        userInfo()
                    }
                }
            }
        }
    }

    fun userInfo() {
        hold({
            server.userinfo().apply {
                body()?.let {
                    if (it.isSuccess) {
                        StoreUtil.saveBean(getApplication(), it.data!!)
                    }
                }
            }
        }, success = {
            callUser.value = it
        })
    }

    //getOrder
    fun getRechargeOrder() {
        hold({
            server.current_recharge()
        }, {
            isShowing.value = true
        }, success = {
            rechargeOrder.value = it
        }, complete = {
            isShowing.value = false
        })
    }


}